<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属楼宇" prop="builderId">
        <el-select v-model="queryParams.builderId" filterable remote @focus="remoteMethods"
                   :remote-method="remoteMethod"
                   :loading="buildingloading" placeholder="请输入所属楼宇" clearable size="small">
          <el-option
            v-for="dict in optionBuildingList"
            :key="dict.id"
            :label="dict.buildingName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房间号" prop="roomnumber">
        <el-input
          v-model="queryParams.roomnumber"
          placeholder="请输入房间号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租赁状态" prop="houseStatus">
        <el-select v-model="queryParams.houseStatus" placeholder="" clearable size="small">
          <el-option
            v-for="dict in dict.type.house_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['house:house:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['house:house:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['house:house:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['house:house:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
      <el-table-column fixed type="selection" width="55" align="center"/>
      <el-table-column label="房间号" align="center" prop="roomnumber"/>
      <el-table-column label="所属楼层" align="center" prop="houseFloor.floorTitle"/>
      <el-table-column label="所属楼宇" align="center" prop="houseFloor.houseBuilder.buildingName"/>
      <el-table-column label="建筑面积" align="center" prop="area"/>
      <el-table-column label="公摊面积" align="center" prop="publicArea"/>
      <el-table-column label="可租面积" align="center" prop="rentarea"/>
      <el-table-column label="租赁状态" align="center" prop="houseStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.house_status" :value="scope.row.houseStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="租金" align="center" prop="rentMoney"/>
      <el-table-column label="租金类型" align="center" prop="rentUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.unit_type" :value="scope.row.rentUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="物业费" align="center" prop="propertyMoney"/>
      <el-table-column label="物业费类型" align="center" prop="propertyUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.unit_type" :value="scope.row.propertyUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="是否上架" align="center" prop="isMarketable">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isMarketable" :active-value="1" :inactive-value="0"
                     @change="hitTheShelf($event,scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column width="150" fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['house:house:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['house:house:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房间对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属楼宇" prop="builderId">
          <el-select v-model="form.builderId" filterable remote @focus="remoteMethods" @change="builderChange"
                     :remote-method="remoteMethod"
                     :loading="buildingloading" placeholder="请输入所属楼宇" clearable size="small">
            <el-option
              v-for="dict in optionBuildingList"
              :key="dict.id"
              :label="dict.buildingName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属楼层" prop="floorId">
          <el-select v-model="form.floorId" filterable remote @focus="floorremoteMethods"
                     :remote-method="floorremoteMethod" :loading="buildingloading" placeholder="请输入所属楼层" clearable
                     size="small">
            <el-option
              v-for="dict in optionFloorList"
              :key="dict.id"
              :label="dict.floorTitle"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="roomnumber">
          <el-input v-model="form.roomnumber" placeholder="请输入房间号"/>
        </el-form-item>
        <el-form-item label="建筑面积" prop="area">
          <el-input-number v-model="form.area" controls-position="right" :min="0"></el-input-number>
          平米
        </el-form-item>
        <el-form-item label="公摊面积" prop="publicArea">
          <el-input-number v-model="form.publicArea" controls-position="right" :min="0"></el-input-number>
          平米
        </el-form-item>
        <el-form-item label="可租面积" prop="rentarea">
          <el-input-number v-model="form.rentarea" controls-position="right" :min="0"></el-input-number>
          平米
        </el-form-item>
        <el-form-item class="selectUnit" label="租金" prop="rentMoney">
          <el-input-number v-model="form.rentMoney" controls-position="right" :min="0"></el-input-number>
          <el-select v-model="form.rentUnit" placeholder="请选择租金单位">
            <el-option
              v-for="(dict,i) in dict.type.unit_type"
              :key="i"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="selectUnit" label="物业费" prop="propertyMoney">
          <el-input-number v-model="form.propertyMoney" controls-position="right" :min="0"></el-input-number>
          <el-select v-model="form.propertyUnit" placeholder="请选择物业费单位">
            <el-option
              v-for="(dict,i) in dict.type.unit_type"
              :key="i"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss">
  .selectUnit {
    .el-form-item__content {
      display: flex;
    }
    >div{
      flex:1
    }
  }
</style>
<script>
  import {listBuild} from "@/api/build/build";
  import {listFloor} from "@/api/floor/floor";
  import {listHouse, getHouse, delHouse, addHouse, updateHouse} from "@/api/house/house";

  export default {
    name: "House",
    dicts: ['house_status', 'unit_type', 'reserve_status'],
    data() {
      var validatePass = (rule, value, callback) => {
        if (!value && value != 0) {
          callback(new Error('租金总计不能为空！'));
        } else if (parseFloat(value) <= 0) {
          callback(new Error('租金总计需大于0！'));
        } else {
          callback();
        }
      }
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 房间表格数据
        houseList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          builderId: null,
          area: null,
          roomnumber: null,
          rentarea: null,
          houseStatus: null,
          floorId: null,
          rentMoney: null,
          rentUnit: null,
          propertyMoney: null,
          propertyUnit: null,
          isMarketable: null,
          publicArea: null,
          reserveStatus: null,
          contractEndTime: null
        },
        // 表单参数
        form: {
          rentMoney:0,
          propertyMoney:0
        },
        // 表单校验
        rules: {
          builderId: [
            {required: true, message: "所属楼宇名称不能为空！", trigger: "blur"}
          ],
          floorId: [
            {required: true, message: "所属楼层名称不能为空！", trigger: "blur"}
          ],
          roomnumber: [
            {required: true, message: "房间号名称不能为空！", trigger: "blur"}
          ],
          rentarea: [{
            validator: validatePass, trigger: 'change', required: true
          }],
          rentMoney:[{
            validator: validatePass, trigger: 'change', required: true
          }],
          propertyMoney:[{
            validator: validatePass, trigger: 'change', required: true
          }]
        },
        //楼宇列表
        buildingList: [],
        optionBuildingList: [],
        buildingloading: false,
        //楼层列表
        floorList: [],
        optionFloorList: [],
        //单位列表
        unit_type_list: []
      };
    },
    created() {
      this.getList();
      // 获取楼宇列表
      listBuild().then(response => {
        this.buildingList = response.rows;
        this.optionBuildingList = this.buildingList;
      });
      //获取单位列表
      this.getDicts("unit_type").then(response => {
        this.unit_type_list = response.data;
        this.reset();
      });
    },
    methods: {
      // 楼宇下拉聚焦
      remoteMethods() {
        this.optionBuildingList = this.buildingList;
      },
      // 楼宇下拉搜索选择
      remoteMethod(query) {
        if (query !== '') {
          this.buildingloading = true;
          setTimeout(() => {
            this.buildingloading = false;
            this.optionBuildingList = this.buildingList.filter(item => {
              return item.buildingName.toLowerCase().indexOf(query.toLowerCase()) > -1;
            });
          }, 200);
        } else {
          this.optionBuildingList = this.buildingList;
        }
      },
      // 楼宇改变，楼层更新
      builderChange() {
        this.form.floorId = null;
        this.optionFloorList = [];
      },
      //楼层下拉聚焦
      floorremoteMethods() {
        if (this.form.builderId) {
          listFloor({builderId: this.form.builderId}).then(response => {
            console.log(response)
            this.floorList = response.rows;
            this.optionFloorList = this.floorList;
          });
        }
      },
      // 楼层下拉搜索选择
      floorremoteMethod(query) {
        if (query !== '') {
          this.buildingloading = true;
          setTimeout(() => {
            this.buildingloading = false;
            this.optionFloorList = this.floorList.filter(item => {
              return item.floorTitle.toLowerCase().indexOf(query.toLowerCase()) > -1;
            });
          }, 200);
        } else {
          this.optionFloorList = this.floorList;
        }
      },
      //上架下架
      hitTheShelf(event, query) {
        // console.log(event,query);
        updateHouse(query).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
        });
      },
      /** 查询房间列表 */
      getList() {
        this.loading = true;
        listHouse(this.queryParams).then(response => {
          this.houseList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          builderId: null,
          area: null,
          remark: null,
          roomnumber: null,
          rentarea: null,
          houseStatus: 0,
          floorId: null,
          rentMoney: null,
          rentUnit: null,
          propertyMoney: null,
          propertyUnit: null,
          publicArea: null,
          reserveStatus: 0
        };
        this.form.rentUnit = this.unit_type_list[0].dictValue;
        this.form.propertyUnit = this.unit_type_list[0].dictValue;
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加房间";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getHouse(id).then(response => {
          this.form = JSON.parse(JSON.stringify(response.data));
          this.form.propertyUnit=String(this.form.propertyUnit);
          this.form.rentUnit=String(this.form.rentUnit);
          console.log(this.form);
          this.open = true;
          this.title = "修改房间";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateHouse(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addHouse(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除房间编号为"' + ids + '"的数据项？').then(function () {
          return delHouse(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('house/house/export', {
          ...this.queryParams
        }, `house_${new Date().getTime()}.xlsx`)
      }
    }
  }
  ;
</script>
